<template>
  <a-modal :width="1200" v-model:visible="showCampaignDetail" title="广告活动" title-align="start" :mask-closable="false" :footer="false" @cancel="closedDialog">
    <a-row class="detail-item">
      <a-col :span="8">
        <div class="flex">
          <p class="label">店铺：</p>
          <p class="val">{{ currentData.shopName }}</p>
        </div>
      </a-col>
      <a-col :span="9">
        <div class="flex">
          <p class="label">广告活动：</p>
          <div>
            <p class="val">{{ currentData.campaignName }}</p>
            <p class="info">{{ currentData.campaignId }}</p>
          </div>
        </div>
      </a-col>
      <a-col :span="5">
        <div class="flex">
          <p class="label">预算：</p>
          <p class="val">{{ getCurrencySymbol() }}{{ currentData.budgetAmount }}</p>
        </div>
      </a-col>
    </a-row>
    <a-row class="detail-item">
      <a-col :span="8">
        <div class="flex">
          <p class="label">状态：</p>
          <p class="val">{{ AdStatus[currentData.state] }}</p>
        </div>
      </a-col>
      <a-col :span="9">
        <div class="flex">
          <p class="label">组合名称：</p>
          <p class="val">{{ currentData.portfolioName }}</p>
        </div>
      </a-col>
      <a-col :span="5">
        <div class="flex">
          <p class="label">销售员：</p>
          <p class="val">{{ currentData.operationsName }}</p>
        </div>
      </a-col>
    </a-row>
    <a-row class="detail-item">
      <a-col :span="8">
        <div class="flex">
          <p class="label">广告类型：</p>
          <p class="val">{{ AdTypes[currentData.adType] }}</p>
        </div>
      </a-col>
      <a-col :span="9">
        <div class="flex">
          <p class="label">投放类型：</p>
          <p class="val">{{ currentData.targetingType }}</p>
        </div>
      </a-col>
      <a-col :span="5">
        <div class="flex">
          <p class="label">竞价策略：</p>
          <p class="val">{{ DynamicBudgetStrategy[currentData.dynamicBudgetStrategy] || '未知' }}</p>
        </div>
      </a-col>
    </a-row>
    <a-tabs v-model:active-key="currentTab" @change="changeStatus" style="margin-bottom: 10px">
      <a-tab-pane key="指标趋势" title="指标趋势" />
      <a-tab-pane key="风险处理" title="风险处理" />
      <a-tab-pane key="处理日志" title="处理日志" />
      <a-tab-pane key="操作日志" title="操作日志" />
      <a-tab-pane key="留言" title="留言" />
    </a-tabs>
    <div class="detail-con-w">
      <!-- 趋势 -->
      <template v-if="currentTab == '指标趋势'">
        <a-range-picker v-model="timeVal" shortcuts-position="left" :shortcuts="rangeShortcuts()" style="width: 260px" @change="startSearch" />
        <!-- 图表 -->
        <AdChart ref="adChartRef" type="campaign" :searchParams="searchParam" :height="150" />
        <!-- table -->
        <a-table size="mini" :scroll="{ y: '100%' }" class="table-singe-line" :bordered="false" :pagination="false" :data="dateTableList">
          <template #columns>
            <a-table-column title="日期" :width="85" :sortable="sortable" data-index="reportDate" />
            <a-table-column title="每日预算" align="right" :width="80" data-index="budgetAmount">
              <template #cell="{ record }">
                <p>
                  <span>{{ getCurrencySymbol() }}</span>
                  <span>{{ record.budgetAmount }}</span>
                </p>
              </template>
            </a-table-column>
            <a-table-column v-for="(item, index) of columns" :key="index" align="right" :width="item.width" :title="item.title" :sortable="item.sortable" :data-index="item.dataIndex">
              <template v-if="['ctr', 'cvr', 'acos'].includes(item.dataIndex)" #cell="{ record }">
                <p v-if="record[item.dataIndex] || record[item.dataIndex] === 0">{{ Number(record[item.dataIndex]).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
              <template v-else-if="['cost', 'cpc', 'cpa', 'saleAmount', 'roas'].includes(item.dataIndex)" #cell="{ record }">
                <p v-if="record[item.dataIndex] || record[item.dataIndex] === 0">
                  <span v-if="item.dataIndex != 'roas'">$</span>
                  <span>{{ Number(record[item.dataIndex]).toFixed(2) }}</span>
                </p>
                <p v-else>--</p>
              </template>
              <template v-else #cell="{ record }">
                <p>{{ record[item.dataIndex] }}</p>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
      <!-- 风险处理 -->
      <div style="width: 600px" v-if="currentTab == '风险处理'">
        <HandleRisk :adList="[currentData]" @cancel="closedDialog" @success="handleRiskUpdate" />
      </div>
      <!-- 处理日志 -->
      <HandleRiskLog v-if="currentTab == '处理日志'" :currentData="currentData" />
      <!-- 操作日志 -->
      <div class="table-gl-w" v-if="currentTab == '操作日志'">
        <AdHandleLog :currentData="currentData" :entityTypes="['CAMPAIGN']" />
      </div>
      <!-- 留言 -->
      <RiskComment v-if="currentTab == '留言'" :currentData="currentData" @update="isUpdate = true" />
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, nextTick, onMounted } from 'vue'
  import { campaignTrendCharts } from '@/api/advert'
  import { AdStatus, AdTypes, DynamicBudgetStrategy } from '../../types'
  import AdChart from './adChart.vue'
  import { getStartAndEndTime, rangeShortcuts } from '@/utils/timeFormat'
  import { marketPlaceList, currencySymbol } from '@/utils/globalData'
  import HandleRisk from './handleRisk.vue'
  import HandleRiskLog from './handleRiskLog.vue'
  import RiskComment from './riskComment.vue'
  import AdHandleLog from './adHandleLog.vue'
  onMounted(() => {
    if (props.tabName == '指标趋势') {
      startSearch()
    }
  })
  const emit = defineEmits(['closed', 'update'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentData: {
      type: Object,
      default: () => {},
    },
    tabName: {
      type: String,
      default: '指标趋势',
    },
  })
  const sortable = {
    sortDirections: ['ascend', 'descend'],
  }
  const columns = [
    {
      title: '曝光量',
      dataIndex: 'impressions',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: '点击量',
      dataIndex: 'clicks',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: 'CTR',
      dataIndex: 'ctr',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: '花费',
      dataIndex: 'cost',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: 'CPC',
      dataIndex: 'cpc',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: 'CVR',
      dataIndex: 'cvr',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: 'CPA',
      dataIndex: 'cpa',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: '总单量',
      dataIndex: 'purchasesOrder',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: '商品销量',
      dataIndex: 'purchasesSale',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: '销售额',
      dataIndex: 'saleAmount',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: 'ACOS',
      dataIndex: 'acos',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: 'ROAS',
      dataIndex: 'roas',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
  ]
  const showCampaignDetail = ref(props.isShow)
  const searchParam = ref<any>({
    shopId: props.currentData.shopId,
    adType: props.currentData.adType,
    isDetail: true,
    campaignId: props.currentData.campaignId,
    portfolioIds: props.currentData.portfolioId ? [props.currentData.portfolioId] : null,
  })
  const timeVal = ref<Array<string>>(getStartAndEndTime('last_30_days'))
  const adChartRef = ref()
  const dateTableList = ref([])
  const tableLoading = ref(false)
  const currentTab = ref(props.tabName)
  const isUpdate = ref(false)

  function changeStatus(status: any) {
    if (status == '指标趋势') {
      startSearch()
    }
  }
  // 显示货币符号
  function getCurrencySymbol() {
    let currency = marketPlaceList[props.currentData.marketplaceId]?.currency
    return currencySymbol[currency]
  }
  // 设置初始化查询条件
  function startSearch() {
    searchParam.value.startDate = timeVal.value[0]
    searchParam.value.endDate = timeVal.value[1]
    nextTick(async () => {
      adChartRef.value.refreshData()
      getDateTableList()
    })
  }
  // 获取趋势详细数据
  async function getDateTableList() {
    tableLoading.value = true
    let res: any = await campaignTrendCharts(searchParam.value)
    tableLoading.value = false
    dateTableList.value = res?.data || []
  }
  // 处理风险
  function handleRiskUpdate() {
    isUpdate.value = true
    closedDialog()
  }

  // 关闭
  function closedDialog() {
    showCampaignDetail.value = false
    emit('closed')
    if (isUpdate.value) {
      emit('update')
    }
  }
</script>
<style lang="less" scoped>
  .detail-item {
    margin-bottom: 5px;
    height: 30px;
    line-height: 14px;
    .label {
      width: 80px;
      text-align: right;
    }
    .val {
      color: #666;
    }
    .info {
      font-size: 12px;
      color: #999;
    }
  }

  .detail-con-w {
    height: calc(84vh - 250px);
    overflow-y: hidden;
    display: flex;
    flex-direction: column;
    .arco-table {
      flex: 1;
      height: 100%;
      overflow-y: hidden;
    }
  }

  :deep(.arco-table-sorter) {
    margin-left: 2px;
  }
</style>
